<template>
  <div class="h-flow-menu-context" :style="contextStyle">
    <template v-for="item in menuContext">
      <component :is="renderItem(item)"/>
    </template>
  </div>
</template>
<script>
import Vue from 'vue';

export default {
  name: 'MenuContext',
  props: {
    x: {
      type: Number,
      default: 0,
    },
    y: {
      type: Number,
      default: 0,
    },
    menuContext: {
      type: Array,
      default: () => [],
    }
  },
  mounted() {
    setTimeout(() => this.$nextTick(this.listenBlur), 100);
  },
  beforeDestroy() {
    document.body.removeEventListener('click', this.closeEvent);
  },
  methods: {
    listenBlur() {
      let that = this;
      this.closeEvent = function close() {
        that.$emit('close');
        console.log('menu context close');
        document.body.removeEventListener('click', this.closeEvent);
      };
      document.body.addEventListener('click', this.closeEvent);
    },
    renderItem(item) {
      let h = this.$createElement;
      return Vue.component('item', {
        render: () => h('div', {
          on: {
            click: (e) => this.clickItem(item, e)
          },
          class: ['h-flow-menu-item', {'h-flow-menu-item-danger': item.danger}]
        }, [this.renderIcon(item), this.renderTitle(item)])
      });
    },
    clickItem(item, e) {
      e.stopPropagation();
      if (item.click) {
        item.click();
      }
    },
    renderIcon(item) {
      let h = this.$createElement;
      return h('div', {class: ['h-flow-menu-item-icon']}, [item.icon]);
    },
    renderTitle(item) {
      let h = this.$createElement;
      return h('div', {class: ['h-flow-menu-item-title']}, [item.title]);
    },
  },
  computed: {
    contextStyle() {
      return {
        left: `${this.x}px`,
        top: `${this.y}px`,
      };
    },
  }
};
</script>
<style>
.h-flow-menu-context {
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  background: white;
  border-radius: 8px;
  min-width: 240px;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);
  padding: 10px 0;
}

.h-flow-menu-item {
  padding: 5px;
}

.h-flow-menu-item:hover {
  background: #e6f7ff;
  transition: background 0.2s;
  color: #1890ff
}

.h-flow-menu-item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;

  user-select: none;
  cursor: pointer;
}

.h-flow-menu-item-title {
  flex: 1;
  padding-left: 5px;
}

.h-flow-menu-item-icon {
  width: 25px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.h-flow-menu-item-danger:hover {
  background: #fff1f0;
  color: #ff4d4f;
}
</style>